package com.zym.framework.grid;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zym.application.exception.AppBugExcepiton;
import com.zym.application.model.ReturnModel;
import com.zym.application.session.Http;
import com.zym.application.session.HttpCall;
import com.zym.application.utils.LogUtils;
import com.zym.framework.constants.Grid;
import com.zym.framework.constants.color;
import com.zym.framework.exception.ZymFwExcepiton;
import com.zym.framework.model.ParseModel;
import com.zym.framework.model.SelectModel;
import com.zym.framework.utlis.FxmlUtil;
import com.zym.framework.utlis.IviewParseUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.paint.Paint;
import javafx.util.Callback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * QQ 165149324
 * 臧英明
 *通用封装类
 * @author
 * @create 2021-02-07
 */
public class ZymGrid {
    @FXML
    private TableView table;
    @FXML
    private ScrollPane scrollPane;
    @FXML
    private Label dataSize;
    @FXML
    private Label dataTime;
    @FXML
    private Label dataCount;
    @FXML
    private ToolBar toobar;
    @FXML
    private ChoiceBox limit;
    @FXML
    private Label ms;

    private ParseModel parseModel;
    private CheckBox titleCheckBox;


    private ObservableList data = FXCollections.observableArrayList();
    private String url;
    private Map parMap = new HashMap();
    private Map dataBook;


    public static FXMLLoader create (){
        try {
            FXMLLoader fxmlLoader = new FXMLLoader();
            fxmlLoader.setLocation(FxmlUtil.class.getResource("/component/grid/ZymGrid.fxml"));
            fxmlLoader.load();
            return fxmlLoader;
        } catch (IOException var3) {
            throw new ZymFwExcepiton(var3);
        }
    }


    public void query(Map map){
        if(url == null ){
            throw new AppBugExcepiton("没有设置URL");
        }
        parMap.clear();
        parMap.put("listNumber",limit.getValue());
        if(map != null){
            parMap.putAll(map);
        }
        long start = System.currentTimeMillis();
        Http.post(url, parMap, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                Object obj = returnModel.getObj();
                if(obj instanceof JSONObject){
                    addRequestData((JSONObject) obj,start);
                }
                if(obj instanceof JSONArray){
                    JSONObject jsonObject = new JSONObject();
                    JSONArray jsonArray = (JSONArray) obj;
                    jsonObject.put("datas",jsonArray);
                    jsonObject.put("number",jsonArray.size());
                    jsonObject.put("count",jsonArray.size());
                    addRequestData(jsonObject,start);
                }

            }
        });
    }
   private void addRequestData(JSONObject jsonObject,long startTime){
       JSONArray datas = jsonObject.getJSONArray("datas");
       dataSize.setText(jsonObject.getString("number"));
       dataCount.setText(jsonObject.getString("count"));
       long time = System.currentTimeMillis() - startTime;
       if(time >= 150){
           dataTime.setTextFill(Paint.valueOf(color.RED));
           ms.setTextFill(Paint.valueOf(color.RED));
       }else {
           dataTime.setTextFill(Paint.valueOf(color.GREEN));
           ms.setTextFill(Paint.valueOf(color.GREEN));
       }
       dataTime.setText(String.valueOf(time));
       LogUtils.println("查询数据" + url);
       data.clear();
       //修复全选后点刷新 主勾选还在
       if(titleCheckBox != null && titleCheckBox.isSelected()){
           titleCheckBox.setSelected(false);
       }
       if(datas !=null){
           data.setAll(datas);
       }
   }
    public void addData(List datas){
        data.setAll(datas);
    }
    public void addData(JSONObject jsonObject,long startTime){
        addRequestData(jsonObject,startTime);
    }

    public String getUrl() {
        return url;
    }

    public void addColumns(List<TableColumn> tableColumns){
        table.getColumns().addAll(tableColumns);
        table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); //设置多选
        for (int i = 0; i <tableColumns.size() ; i++) { //添加check监听事件
            TableColumn tableColumn = tableColumns.get(i);
            if(Grid.SELECT.equals(tableColumn.getId())){
                CheckBox checkBox = (CheckBox) tableColumn.getGraphic();
                this.titleCheckBox = checkBox;
                checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
                    public void changed(ObservableValue<? extends Boolean> ov,
                                        Boolean old_val, Boolean new_val) {
                        updateCheckSelectAll(new_val);
                    }
                });
                break;
            }
        }
//        table.setRowFactory( tv -> {
//            TableRow<JSONObject> row = new TableRow<JSONObject>();
//            row.setOnMouseClicked(event -> {
//                if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
//                    JSONObject emailInfo = row.getItem();
//                    System.out.println(emailInfo);
//                }
//            });
//            return row ;
//        });

    }
    public void setRowFactory(Callback<TableView, TableRow> callback){
        table.setRowFactory(callback);
    }

    private void updateCheckSelectAll(boolean is){
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = (JSONObject) data.get(i);
            jsonObject.put(Grid.SELECT,is);
        }
        table.refresh();
    }


    public void addColumns(String JSONString,Map dataBook){
        parseModel = IviewParseUtils.parseGrid(JSONString, dataBook);
        addColumns(parseModel.getTableColumns());
    }

    public List<SelectModel> getSelectModels(){
        if(parseModel == null){
            throw new AppBugExcepiton("请先加入行");
        }
        return parseModel.getSelectModels();
    }

    public void setUrl(String url) {
        table.setItems(data);
        this.url = url;
    }
    public void setWinWidth(int winWidth) {
        this.scrollPane.setPrefWidth(winWidth);
        autoView();
    }

    public void setWinHeight(int winHeight) {
        this.scrollPane.setPrefHeight(winHeight);
        autoView();
    }



    public void initView() {
        autoView();
    }

    public void initView(String tableColumnsStr) {
        this.addColumns(tableColumnsStr,dataBook);
        autoView();
    }

    /**
     * 初始化
     */
    public void initView(String url,String tableColumnsStr) {
        initView(url,tableColumnsStr,null);
    }
    public void initView(String url,String tableColumnsStr,Map dataBook) {
        this.dataBook = dataBook;
        this.addColumns(tableColumnsStr,dataBook);
        this.setUrl(url);
        autoView();
    }
    private void autoView() {
        table.setPrefHeight(scrollPane.getPrefHeight()-3);
        table.setPrefWidth(scrollPane.getPrefWidth()-3);
        toobar.setLayoutY(table.getPrefHeight()+1);
        toobar.setPrefWidth(scrollPane.getPrefWidth());
    }

    public List<String> getSelectId() {
       return getSelectValue("ID");
    }
    public List getSelectData() {
        List  ids = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            Object o = data.get(i);
            Map data = (Map) o;
            if(data.containsKey(Grid.SELECT)){
                Boolean $_select = (Boolean) data.get(Grid.SELECT);
                if($_select){
                    ids.add(data);
                }
            }
        }
        return ids;
    }
    public List<String> getSelectValue(String key) {
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            Object o = data.get(i);
            Map data = (Map) o;
            if(data.containsKey(Grid.SELECT)){
                Boolean $_select = (Boolean) data.get(Grid.SELECT);
                if($_select){
                    ids.add(data.get(key).toString());
                }
            }
        }
        return ids;
    }
//    public Parent getView(){
//    }
}
